using System;
using NHibernate;

namespace Entity.Hibernate
{
    public class PersistentObject<T>
    {
        public virtual Object ID { get; set; }

        public virtual bool IsPersisted
        {
            get { return ID != null; }
        }

        public virtual void Save()
        {
            ISession session = NHibernateSessionManager.Instance.GetSession();
            if (!IsPersisted)
                session.Save(this);
            else
                session.SaveOrUpdateCopy(this);

            session.Flush();
        }

        public virtual void Delete()
        {
            ISession session = NHibernateSessionManager.Instance.GetSession();
            session.Delete(this);
            session.Flush();
        }

        public virtual T Clone()
        {
            return Clone();
        }

        /// <summary>
        /// Returns a valid populated object or a null reference        
        /// </summary>        
        public static T Get(Object id)
        {
            ISession session = NHibernateSessionManager.Instance.GetSession();
            return session.Get<T>(id);
        }
    }
}